<template>
  <div>
    <!--面包屑导航区域-->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!--卡片视图区域-->
    <el-card>
      <!--搜索与添加区域-->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="根据用户名查找信息"
            v-model="queryInfo.query"
            @keydown.enter.native="getUser"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUser"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">
            添加用户
          </el-button>
        </el-col>
      </el-row>
      <!--用户列表区域-->
      <el-table :data="userlist" border stripe>
        <el-table-column label="索引" type="index"></el-table-column>
        <el-table-column label="编号" prop="id"></el-table-column>
        <el-table-column label="真实姓名" prop="realname"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="phone"></el-table-column>
        <!-- <el-table-column
          label="等级"
          prop="levelId.levelName"
        ></el-table-column> -->
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <!--修改按钮-->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row.userName)"
            ></el-button>
            <!--删除按钮-->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeUserById(scope.row.userId)"
            ></el-button>
            <!--分配角色按钮-->
            <!-- 分配按钮 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="角色分配"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="setRole(scope.row)"
              ></el-button>
            </el-tooltip>
            <!-- <el-button type="warning" icon="el-icon-setting" size="mini" @click="setRole(scope.row)"></el-button> -->
          </template>
        </el-table-column>
      </el-table>

      <!--分页区域-->
      <!-- 暂时没有需求 -->
      <!-- <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 8]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination> -->
    </el-card>

    <!--添加用户的对话框-->
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
      @keydown.enter.native="adduser"
    >
      <!--内容主体区域-->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="80px"
      >
        <el-form-item label="用户id" prop="userId">
          <el-input v-model="addForm.id"></el-input>
        </el-form-item>
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="addForm.realname"></el-input>
        </el-form-item>
        <!-- 头像不需要上传 -->
        <!-- <el-form-item label="编号" prop="teachernum">
          <el-input v-model="addForm.teachernum"></el-input>
        </el-form-item>
        <el-form-item label="真名" prop="realName">
          <el-input v-model="addForm.realName"></el-input>
        </el-form-item> -->
      </el-form>
      <!--底部区域-->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="adduser">确 定</el-button>
      </span>
    </el-dialog>

    <!--修改用户对话框-->
    <el-dialog
      title="修改用户"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
      @keydown.enter.native="editUserInfo"
    >
      <!--内容主体区域-->
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名">
          <el-input v-model="editForm.userName" disabled></el-input>
        </el-form-item>
        <!-- <el-form-item label="真名">
          <el-input v-model="editForm.levelId"></el-input>
        </el-form-item> -->
        <el-form-item label="真名">
          <el-input v-model="editForm.realName"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="editForm.phone"></el-input>
        </el-form-item>
      </el-form>
      <!--底部区域-->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!--用户删除弹框-->
  </div>
</template>

<script>
export default {
  data() {
    // 验证邮箱的规则
    var checkEmail = (rule, value, cb) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-z0-9_-]+)@([\da-z-]+)\.([a-z]{2,6})$/
      if (regEmail.test(value)) {
        // 合法的邮箱
        return cb()
      }
      cb(new Error('请输入合法的邮箱'))
    }
    // 验证手机号的规则
    var checkMobile = (rule, value, cb) => {
      // 验证手机号的正则表达式
      const regMobile = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的手机号'))
    }
    return {
      // 获取用户列表的参数对象
      queryInfo: {
        query: ''
        // pagenum:3,
        // 当前的页数
        // pagesize: 1
        // 当前每页显示多少条数据
      },
      // 用户列表数据
      userlist: [
        {
          userName: '210711023',
          realName: '王莹莹',
          email: '2621233526@qq.com',
          phone: '15117563455'
        },
        {
          userName: '210711024',
          realName: '李明凯',
          email: '15142623535@163.com',
          phone: '13285678989'
        }
      ],
      // 总共的用户数量
      // total: 4,
      // 控制添加用户对话框的显示与隐藏
      addDialogVisible: false,
      // 控制修改用户对话框的显示与隐藏
      editDialogVisible: false,
      // 分配角色对话框的显示与隐藏
      // setRoleDialogVisible: false,
      // 添加用户的表单数据
      addForm: {
        id: '',
        username: '',
        password: '',
        realname: ''
      },
      // 添加表单的验证规则对象
      addFormRules: {
        id: [{ required: true, message: '请输入用户id', trigger: 'blur' }],
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 30, message: '密码太短', trigger: 'blur' }
        ],
        level: [{ required: true, message: '请输入用户等级', trigger: 'blur' }],
        teachernum: [
          { required: true, message: '请输入用户编号', trigger: 'blur' }
        ],
        realname: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入电话', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 查询到的用户信息对象
      editForm: {},
      // 修改表单的验证规则对象
      editFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ], // 验证规则：validitor；触发时期：在失去焦点的时候
        phone: [
          { required: true, message: '请输入电话', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 需要被分配角色的用户信息
      userInfo: {},
      // 所有角色的数据列表
      rolesList: [
        { id: 0, roleName: '管理员' },
        { id: 1, roleName: '教师' }
      ],
      // 已选中的角色Id值
      selectedRoleId: ''
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    async getUserList() {
      console.log('getUserList被调用')
      const { data: res } = await this.$axios.get('/api/admin/getUserAll')
      console.log(res)
      if (!res) {
        return this.$message.error('获取用户列表失败')
      }
      this.$message.success('获取用户列表成功')
      this.userlist = res
      // this.total = res.length
    },
    // 监听pagesize改变的事件
    // 每页显示多少条数据
    // handleSizeChange(newSize) {
    //   this.queryInfo.pagesize = newSize
    //   console.log(newSize)
    //   this.getUserList()
    // },
    // // 显示有多少页
    // handleCurrentChange(newPage) {
    //   this.queryInfo.pagenum = newPage
    //   this.getUserList()
    //   console.log(newPage)
    // },
    // 监听添加用户对话框的关闭事件
    addDialogClosed() {
      // this.$refs.addFormRef.resetFields()
    },
    // 点击按钮，添加新用户
    adduser() {
      // 预检验，判断值对了再往进添加
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return 
        console.log(valid)
        // 可以发起添加用户的网络请求
        const { data: res } = await this.$axios
          .post('/api/admin/newUserInfo', this.addForm)
          .catch((err) => err)

        console.log(res)
        // if (res.id !== this.addForm.id) {
        //   return this.$message.error('添加用户失败')
        // }

        this.$message.success('添加用户成功')
        // 隐藏添加用户的对话框
        this.addDialogVisible = false
        // 重新获取用户列表数据
        this.getUserList()
      })
    },
    // 展示编辑用户的对话框
    // 根据id查询用户信息
    async showEditDialog(userName) {
      this.editDialogVisible = true
      const { data: res } = await this.$axios.get('/api/admin/getUser', {
        params: {
          userName
        }
      })
      console.log(res)
      this.editForm = res

      this.editDialogVisible = true
    },
    // 监听修改用户对话框的关闭事件
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    // 修改用户信息并提交
    editUserInfo() {
      // 预校验
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return console.log(valid)
        // 可以发起修改用户信息的数据请求
        const { data: res } = await this.$axios.post(
          '/api/admin/getNewUser',
          this.editForm
        )
        console.log('sadklfjl', res)
        // if (res.meta.status !== 200) {
        //   this.$message.error('更新用户信息失败')
        // }
        // 关闭对话框
        this.editDialogVisible = false
        // 刷新数据列表
        this.getUserList()
        // 提示修改成功
        this.$message.success('更新用户信息成功')
      })
    },
    // 根据ID删除对应用户信息
    async removeUserById(id) {
      console.log('idn', id)
      // 弹框询问用户是否删除数据
      // -------------
      const confirmResult = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)
      // --------------
      // 如果用户确认删除，则返回值为字符串 confirm
      // 如果用户取消删除，则返回值为字符串 cancel
      // console.log(confirmResult)
      // ------------------
      console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      // -----------------
      // 可以发起删除用户的网络请求
      const { data: res } = await this.$axios.delete('/api/admin/deleteUser', {
        params: {
          id
        }
      })
      if (res.length === 0) {
        return this.$message.error('删除用户失败')
      }
      this.$message.success('删除用户成功')
      // 隐藏添加用户的对话框
      this.addDialogVisible = false
      // 重新获取用户列表数据
      this.getUserList()
    },
    // 展示分配角色对话框
    // async setRole(userInfo) {
    //   console.log(userInfo)
    //   this.userInfo = userInfo
    //   console.log(this.userInfo)
    //   this.setRoleDialogVisible = true
    // },
    // 分配角色
    async setRole(userInfo) {
      this.userInfo = userInfo
      const { data: res } = await this.$axios.get('/api/admin/newUserLevel', {
        params: {
          userName: this.userInfo.userName
        }
      })
      console.log(res)

      // if (res.meta.status !== 200) {
      //   return this.$message.error('更新角色失败！')
      // }
      if (!res) {
        return this.$message.error('超级管理员是大爹')
      }
      this.$message.success('更新角色成功！')
      this.getUserList()
      this.setRoleDialogVisible = false
    },
    // 监听分配角色对话框的关闭事件
    // setRoleDialogClosed() {
    //   this.selectedRoleId = ''
    //   this.userInfo = {}
    // },
    // 查询一个用户
    async getUser() {
      if (this.queryInfo.query) {
        const { data: res } = await this.$axios.get('/api/admin/getUser', {
          params: {
            userName: this.queryInfo.query
          }
        })
        console.log(res)
        this.userlist = [res]
        this.$message.success('查找成功')
      } else {
        this.$message.error('查找失败')
      }
    }
  }
}
</script>

<style lang="less" scoped></style>
